package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * Created by Levin Alexander
 * and Skryabina Tatyana on 25.11.14.
 */
public class Transport {
    private Socket socket;
    private DataOutputStream out;
    private DataInputStream in;

    public Transport(String ip, int port) throws TransportException {
        try {
            socket = new Socket(ip, port);
            out = new DataOutputStream(socket.getOutputStream());
            in = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            throw new TransportException();
        }
    }

    public void request(String request) throws TransportException {
        try {
            out.writeUTF(request);
            out.flush();
        } catch (IOException | NullPointerException e) {
            throw new TransportException();
        }
    }

    public String response() throws TransportException {
        try {
            return in.readUTF();
        } catch (IOException e) {
            throw new TransportException();
        }
    }

    public void closeSocket() {
        try {
            if (!socket.isClosed()) {
                socket.close();
                System.out.println("Connection closed.");
            }
        } catch (IOException e) {
            System.err.println("Error with close connection");
        }
    }
}
